package com.hpe.aruba.CPPM;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.hpe.aruba.CPPM.enums.SharedPrefFields;
import com.hpe.aruba.CPPM.objects.Token;
import com.hpe.aruba.CPPM.utils.ClearpassUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private static final String MyPREFERENCES = "CPPM_pref";

    @BindView(R.id.input_url)
    EditText _urlText;
    @BindView(R.id.input_client_id)
    EditText _clientIdText;
    @BindView(R.id.input_username)
    EditText _usernameText;
    @BindView(R.id.input_password)
    EditText _passwordText;
    @BindView(R.id.btn_login)
    Button _loginButton;
    @BindView(R.id.savePw)
    Switch _savePwSwitch;
    private RequestQueue queue;
    private ProgressDialog progressDialog;
    private SharedPreferences sharedpreferences;
    private ClearpassUtils clearpassUtils;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        queue = Volley.newRequestQueue(this);
        clearpassUtils = new ClearpassUtils(queue);

        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        Data.sharedPreferences = sharedpreferences;

        String url = sharedpreferences.getString(SharedPrefFields.URL.toString(), null);
        long token_exp = sharedpreferences.getLong(SharedPrefFields.TOKEN_EXP.toString(), 0);
        Token token = new Token();
        token.setExpiration(token_exp);
        if (token.isTokenValid()) {
            token.setToken(sharedpreferences.getString(SharedPrefFields.TOKEN.toString(), null));

            //TODO test if Token is still valid

            Data.token = token.getToken();
            Data.baseUrl = url;
            clearpassUtils.getRoles();
            onLoginSuccess();
        }

        _urlText.setText(url);
        _clientIdText.setText(sharedpreferences.getString(SharedPrefFields.CLIENT_ID.toString(), null));
        _usernameText.setText(sharedpreferences.getString(SharedPrefFields.USERNAME.toString(), null));
        String password = sharedpreferences.getString(SharedPrefFields.PASSWORD.toString(), null);
        _passwordText.setText(password);
        if (password != null) {
            _savePwSwitch.setChecked(true);
        }
    }

    @OnClick(R.id.btn_login)
    public void login() {
        Log.d(TAG, "Login");

        if (!validate()) {
            onLoginFailed("");
            return;
        }

        _loginButton.setEnabled(false);

        progressDialog = new ProgressDialog(LoginActivity.this,
                R.style.AppTheme_Dark_Dialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage(getResources().getString(R.string.authenticating));
        progressDialog.show();

        String url = _urlText.getText().toString();
        /*add https if it doesnt start with http(s)*/
        if (!(url.startsWith("http://") || url.startsWith("https://"))) url = "https://" + url;
        String clientId = _clientIdText.getText().toString();
        String username = _usernameText.getText().toString();
        String password = _passwordText.getText().toString();

        SharedPreferences.Editor edit = sharedpreferences.edit();
        edit.putString(SharedPrefFields.URL.toString(), url);
        edit.putString(SharedPrefFields.CLIENT_ID.toString(), clientId);
        edit.putString(SharedPrefFields.USERNAME.toString(), username);
        edit.putString(SharedPrefFields.PASSWORD.toString(), _savePwSwitch.isChecked() ? password : null);
        edit.apply();

        Data.baseUrl = url;
        clearpassUtils.getToken(username, password, clientId, this);
    }

    @Override
    public void onBackPressed() {
        // Disable going back to the MainActivity
        moveTaskToBack(true);
    }

    public void onLoginSuccess() {
        Intent intent = new Intent(this, ManageMacsActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
        _loginButton.setEnabled(true);
        finish();
    }

    public void onLoginFailed(String detail) {
        Toast.makeText(getBaseContext(), "Login failed " + detail
                , Toast.LENGTH_LONG).show();
        progressDialog.dismiss();
        _loginButton.setEnabled(true);
    }

    public boolean validate() {
        boolean valid = true;

//        String email = _emailText.getText().toString();
        String password = _passwordText.getText().toString();

//        if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
//            _emailText.setError("enter a valid email address");
//            valid = false;
//        } else {
//            _emailText.setError(null);
//        }

        if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
            _passwordText.setError("between 4 and 10 alphanumeric characters");
            valid = false;
        } else {
            _passwordText.setError(null);
        }

        return valid;
    }

    public void processToken(Token token) {

        SharedPreferences.Editor edit = sharedpreferences.edit();
        edit.putString(SharedPrefFields.TOKEN.toString(), token.getToken());
        edit.putLong(SharedPrefFields.TOKEN_EXP.toString(), token.getExpiration());
        edit.apply();

        Data.token = token.getToken();

        clearpassUtils.getRoles();
        
        onLoginSuccess();
//         onLoginFailed();
        progressDialog.dismiss();
    }
}
